package com.linkallcloud.web.deapi;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;

import com.linkallcloud.core.aop.LacAspect;
import com.linkallcloud.core.exception.Exceptions;
import com.linkallcloud.deapi.annotation.DeApi;
import com.linkallcloud.web.processor.DeApiRequestProcessor;

public abstract class DeApiAspect extends LacAspect {

    private static volatile DeApiRequestProcessor singletonLazy;

    public DeApiRequestProcessor processor() {
        if (null == singletonLazy) {
            synchronized (DeApiAspect.class) {
                if (null == singletonLazy) {
                    singletonLazy = new DeApiRequestProcessor(getAppCode(), getAppSecret());
                }
            }
        }
        return singletonLazy;
    }

    public abstract String getAppCode();

    public abstract String getAppSecret();

    public Object checkApi(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Method method = getMethod(joinPoint);
            DeApi faceAnno = method.getAnnotation(DeApi.class);
            if (faceAnno == null) {
                return joinPoint.proceed();
            } else {
                return processor().process(joinPoint, method, faceAnno.check(), false);
            }
        } catch (Throwable e) {
            return Exceptions.makeErrorResult(e);
        }
    }

}
